const md5 = require("md5-node")
const { Service } = require("egg");
class userService extends Service {
    //添加用户
    async addUser(body) {
            try {
                const user = {
                    username: body.username,
                    password: md5(body.password)
                }
                await this.app.model.User.create(user)
                return true
            } catch (error) {
                return false
            }
        }
        //获取用户
    async getUser() {
            try {
                const userList = await this.app.model.User.findAll()
                return userList
            } catch (error) {
                return null
            }
        }
        //删除用户
    async deleteUser(id) {
            try {
                await this.app.model.User.destroy({
                    where: {
                        id
                    }
                })
                return true
            } catch (error) {
                return false
            }
        }
        //更新用户
    async updateUser(id, body) {
            try {
                const user = {
                    password: md5(body.password)
                }
                await this.app.model.User.update(user, {
                    where: {
                        id
                    }
                })
                return true
            } catch (error) {
                return false
            }
        }
        //登录
    async login(username, password) {
        try {
            let user = await this.app.model.User.findOne({
                where: {
                    username
                }
            })
            const usernameFind = user.username.trim()
            const psd = user.password.trim()
            const md5Password = md5(password)
            if (usernameFind === username && md5Password === psd) {
                let token = this.app.jwt.sign({ usernameFind }, this.app.config.jwt.secret)
                return token
            } else {
                return false
            }
        } catch (error) {
            return false
        }
    }
}

module.exports = userService